package listbyorder.access001_100.test17;

import java.util.ArrayList;
import java.util.List;

/**
 * 回溯算法
 * @author code_yc
 * @version 1.0
 * @date 2020/5/28 9:40
 */
public class Solution1 {

    // 经典的回溯方法
    public List<String> letterCombinations(String digits) {
        // 首先创建出自数字对应字符串
        String[] dic = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> res = new ArrayList<>();
        if (digits == null || digits.equals("")) return res;
        getAns(digits, 0, new StringBuilder(), dic, res);
        return res;
    }

    private void getAns(String digits, int cs, StringBuilder path, String[] dic, List<String> res) {
        if (cs == digits.length()) {
            res.add(new String(path));
            return;
        }
        int cur_index = digits.charAt(cs) - '0';
        String cur_str = dic[cur_index];
        for (int j = 0; j < cur_str.length(); j++) {
            path.append(cur_str.charAt(j));
            getAns(digits, cs + 1, path, dic, res);
            path.deleteCharAt(path.length() - 1);  // 回溯
        }
    }
}
